import asyncio

class PerformanceMonitor:
    def __init__(self):
        self.request_times = []
        self.queue_sizes = []
        self._processed_count = 0
        self._successful_count = 0
        self._failed_count = 0
        self._end_to_end_times = []
        self._lock = asyncio.Lock()
        
    async def add_request_time(self, duration: float):
        async with self._lock:
            self.request_times.append(duration) # 直接存储秒数
            if len(self.request_times) > 1000:  # 保持最近1000个请求的记录
                self.request_times.pop(0)
    
    async def add_end_to_end_time(self, duration: float):
        async with self._lock:
            self._end_to_end_times.append(duration) # 直接存储秒数
            if len(self._end_to_end_times) > 1000:
                self._end_to_end_times.pop(0)

    async def add_queue_size(self, size: int):
        async with self._lock:
            self.queue_sizes.append(size)
            if len(self.queue_sizes) > 1000:
                self.queue_sizes.pop(0)
    
    async def increment_processed(self):
        async with self._lock:
            self._processed_count += 1

    async def increment_successful(self):
        async with self._lock:
            self._successful_count += 1

    async def increment_failed(self):
        async with self._lock:
            self._failed_count += 1

    async def get_processed_count(self) -> int:
        async with self._lock:
            return self._processed_count

    async def get_successful_count(self) -> int:
        async with self._lock:
            return self._successful_count

    async def get_failed_count(self) -> int:
        async with self._lock:
            return self._failed_count

    async def get_average_time(self) -> float:
        async with self._lock:
            return sum(self.request_times) / len(self.request_times) if self.request_times else 0
    
    async def get_max_queue_size(self) -> int:
        async with self._lock:
            return max(self.queue_sizes) if self.queue_sizes else 0

    async def get_average_end_to_end_time(self) -> float:
        async with self._lock:
            return sum(self._end_to_end_times) / len(self._end_to_end_times) if self._end_to_end_times else 0 